<template>
    <div style="height: 100%">
        <navbar :title="title" style="border-bottom: 1px solid #ccc;"></navbar>
        <div class="content white-bg" v-show="!isLoading">
            <div v-if="isAllow" style="margin: 20px;">
                <van-row>
                    <!-- 标题 -->
                    <van-col span="6" class="van-col-text">{{ $t('title') }}：</van-col>
                    <van-col span="18" class="van-col-text">{{ detail.ilsTitle }}</van-col>
                    <!-- 上课日期 -->
                    <van-col span="6" class="van-col-text">{{ $t('class_date') }}：</van-col>
                    <van-col span="18" class="van-col-text">{{ detail.ilsDate }}</van-col>
                    <!-- 上课时间 -->
                    <van-col span="6" class="van-col-text">{{ $t('class_time') }}：</van-col>
                    <van-col span="18" class="van-col-text">{{ detail.classTimePeriod }}</van-col>
                    <!-- 讲师 -->
                    <van-col span="6" class="van-col-text">{{ $t('group_instructor') }}：</van-col>
                    <van-col span="18" class="van-col-text">{{ detail.itiName }}</van-col>
                    <!-- 地点 -->
                    <van-col span="6" class="van-col-text">{{ $t('address') }}：</van-col>
                    <van-col span="18" class="van-col-text">{{ detail.ilsPlace }}</van-col>
                    <!-- 培训证明 -->
                    <van-col v-if="buttonType === 3" span="6" class="van-col-text">{{ $t('prove') }}：</van-col>
                    <van-col v-if="buttonType === 3" span="18" class="van-col-text">
                        <van-uploader v-model="fileList" :before-read="beforeUpload" :after-read="uploadFile" accept="image/*" capture="camera" :max-count="1"/>
                    </van-col>
                </van-row>
                <!-- 前往首页、多按钮（人脸签到失败）或者允许多次打卡的情况显示 -->
                <van-row v-if="!showSingleButton || buttonType === 2 || allowMultiple">
                    <van-col span="24">
                        <div style="text-align: center;padding: 18px;">
                            <van-icon v-if="showSingleButton && (buttonType === 2 || allowMultiple)" name="checked" color="#00ba5f" size="100"/>
                            <van-icon v-else name="clear" color="#ff0000" size="100"/>
                        </div>
                        <!-- 多个按钮，显示人脸识别失败 -->
                        <div v-if="!showSingleButton" style="text-align: center;font-size: 18px;font-weight: bold;">
                            <!-- 签到成功 | 签退成功 | 人脸识别失败 -->
                            {{ $t('facial_recognition_failed') }}
                        </div>
                        <!-- 单个按钮，并且按钮类型为2时（前往首页）或者允许多次打卡时表示签到成功或者签退成功 -->
                        <div v-if="showSingleButton && (buttonType === 2 || allowMultiple)" style="text-align: center;font-size: 18px;font-weight: bold;">
                            <!-- 签到成功 | 签退成功 -->
                            {{ (type === 0 ? $t('scan_tips_4') : $t('sign_out_successful')) }}
                        </div>
                        <!-- 单个按钮，并且按钮类型不为2时（前往首页）并且不允许多次打卡表示签到失败或者签退失败 -->
                        <div v-if="showSingleButton && buttonType !== 2 && !allowMultiple" style="text-align: center;font-size: 18px;font-weight: bold;">
                            <!-- 签到失败 | 签退失败 -->
                            {{ (type === 0 ? $t('scan_tips_7') : $t('sign_out_failed')) }}
                        </div>
                    </van-col>
                </van-row>
            </div>
            <div v-else style="margin: 20px;">
                <v-alert type="warning" show-icon>
                    <van-icon name="info-o" slot="icon"/>
                    <template slot>
                        <p> {{ notAllowReason }} </p>
                    </template>
                </v-alert>
            </div>
        </div>
        <!-- 面授课程的底部按钮 -->
        <div class="bottom-button" v-show="!isLoading">
            <!-- 单个按钮样式 -->
            <div class="single-button" v-if="showSingleButton">
                <!-- 确认签到 | 确认签退 -->
                <div v-if="buttonType === 0" class="btn" @click="onConfirm"> {{ type === 0 ? $t('confirm_clock_in') : $t('confirm_clock_out') }}</div>
                <!-- 人脸识别 -->
                <div v-if="buttonType === 1" class="btn" @click="visibleModal = true">{{ $t('face_recognition_check_in') }}</div>
                <!-- 前往首页 -->
                <div v-if="buttonType === 2" class="btn" @click="back">{{ $t('go_home') }}</div>
                <!-- 提交 -->
                <div v-if="buttonType === 3" class="btn" @click="onSubmit(true)">{{ $t('button_submit') }}</div>
                <!-- 提示信息（人脸识别，提交） -->
                <div v-if="buttonType === 1 || buttonType === 3" class="tips">
                    <v-alert type="info" show-icon>
                        <van-icon name="info-o" slot="icon"/>
                        <template slot>
                            <p> {{ tips }} </p>
                        </template>
                    </v-alert>
                </div>
            </div>
            <!-- 未报名 -->
            <div class="multiple-button" v-else-if="buttonType === 4">
                <!-- 前往报名 -->
                <div class="btn" @click="onRegistered">{{ $t('go_to_register') }}</div>
                <!-- 返回首页 -->
                <div class="btn" @click="back">{{ $t('back_home') }}</div>
            </div>
            <!-- 早退 -->
            <div class="multiple-button" v-else-if="buttonType === 5">
                <!-- 继续签退 -->
                <div class="btn" @click="onContinue">{{ $t('continue_signing_off') }}</div>
                <!-- 返回首页 -->
                <div class="btn" @click="back">{{ $t('back_home') }}</div>
            </div>
            <div class="multiple-button" v-else>
                <!-- 重试 -->
                <div class="btn" @click="onRetry">{{ $t('button_retry') }}</div>
                <!-- 提交证据 -->
                <div class="btn" @click="onSubmit(false)">{{ $t('submit_evidence') }}</div>
            </div>
        </div>
        <face-modal ref="faceRef" :visibleModal="visibleModal" @takePictures='takePictures' @takingError='takingError' :busId='ilsId'
            :distinguishType="'SCHEDULE'" :busOpeType="type" @closeFace="closeFace" :showClose="true">
        </face-modal>
        <common-loading :isLoading="isLoading"></common-loading>
    </div>
</template>

<script>
import CommonLoading from '@/components/common/loading';
import {Col, Row, Toast} from 'vant';
import faceModal from '@/components/faceModal/faceModal';
export default {
    name: 'punch-the-clock',
    components: {CommonLoading, vanCol: Col, vanRow: Row, faceModal},
    data() {
        return {
            isLoading: true,
            title: this.$t('training_sign_in'), // 培训签到
            itmId: this.$route.params.itmId, // 项目ID
            ilsId: this.$route.params.ilsId, // 日程ID
            type: this.$route.params.type ? Number(this.$route.params.type) : 0, // 类型：0-签到，1-签退
            isAllow: false, // 是否允许打卡，true-允许，false-不允许
            notAllowReason: '', // 不允许打卡原因
            data: {
                ilsId: '', // 日程ID
                itmId: '', // 项目ID
                type: '', // 类型：0-签到，1-签退
                isProve: 0, // 是否需要证明
                img: '' // 证明图片
            },
            detail: { // 详情
                ilsId: '', // 日程ID
                ilsItmId: '', // 项目ID
                ilsTitle: '', // 标题
                ilsStartTime: '', // 开始时间
                ilsEndTime: '', // 结束时间
                ilsDate: '', // 日期
                classTimePeriod: '', // 上课时间段
                ilsPlace: '', // 地点
                itiName: '', // 讲师
                ilsEnableFace: 0, // 是否启用人脸识别
                ilsFaceTypes: null // 人脸识别类型 CLOCK_IN-签到，CLOCK_OUT-签退
            },
            showSingleButton: true, // 是否显示单个按钮
            buttonType: 0, // 0-确认签到 | 确认签退，1-人脸识别，2-前往首页，3-提交，4-未报名，5-继续
            tips: '', // 提示信息
            fileList: [], // 是否正在上传
            visibleModal: false,
            faceTime: 0,
            faceIndex: 0,
            faceList: [],
            allowMultiple: false // 允许多次打卡
        };
    },
    methods: {
        /**
         * 初始化
         */
        init() {
            this.isLoading = true;
            this.$axios({
                method: 'GET',
                url: `/app/api/trainee/course/lesson/clock/verify/${this.ilsId}`,
                params: {type: this.type}
            }).then(res => {
                let data = res.data;
                switch (data.code) {
                case 200: // 允许打卡
                    this.isAllow = true;
                    this.getDetail();
                    break;
                case 4001: // 未报名
                    this.isAllow = false;
                    this.notAllowReason = data.msg;
                    this.showSingleButton = false;
                    this.buttonType = 4;
                    this.isLoading = false;
                    break;
                case 4002: // 早退提醒
                    this.isAllow = false;
                    this.notAllowReason = data.msg;
                    this.showSingleButton = false;
                    this.buttonType = 5;
                    this.isLoading = false;
                    break;
                default:
                    this.isAllow = false;
                    this.notAllowReason = data.msg;
                    this.showSingleButton = true;
                    this.buttonType = 2;
                    this.isLoading = false;
                    break;
                }
            });
        },
        /**
         * 获取日程详情
         */
        getDetail() {
            this.$axios({
                method: 'GET',
                url: `/app/api/trainee/course/lesson/clock/basic/${this.ilsId}`
            }).then(res => {
                this.detail = res.data;
                this.getRecord();
            });
        },
        getRecord() {
            this.$axios({
                method: 'GET',
                url: `/app/api/trainee/course/lesson/clock/record/${this.ilsId}`,
                params: {type: this.type}
            }).then(res => {
                this.isLoading = false;
                let data = res.data;
                if (data && !data.allow) {
                    this.buttonType = 2;
                } else {
                    this.allowMultiple = data && data.allow; // 允许多次打卡
                    // 开启人脸识别
                    if (this.detail.ilsEnableFace && this.detail.ilsFaceTypes && this.detail.ilsFaceTypes.length > 0) {
                        if (this.type === 0) {
                            this.buttonType = this.detail.ilsFaceTypes.includes('CLOCK_IN') ? 1 : 0;
                            this.tips = this.$t('schedule_tips_1');
                        } else {
                            this.buttonType = this.detail.ilsFaceTypes.includes('CLOCK_OUT') ? 1 : 0;
                            this.tips = this.$t('schedule_tips_2');
                        }
                    }
                }
            });
        },
        /**
         * 上传图片前校验格式
         * */
        beforeUpload(file) {
            const rule = /\.(jpg|jpeg|png|JPG|PNG|JPEG)$/;
            // 判断是否是多文件上传
            if (file instanceof Array && file.length) {
                for (let i = 0; i < file.length; i++) {
                    if (!rule.test(file[i].name)) {
                        Toast.fail(this.$t('upload_tips'));
                        return false;
                    }
                }
            } else {
                if (!rule.test(file.name)) {
                    Toast.fail(this.$t('upload_tips'));
                    return false;
                }
            }
            return true;
        },
        /**
         * 上传文件至服务器
         * */
        uploadFile(file) {
            this.data.img = file.content;
        },
        /**
         * 返回首页
         */
        back() {
            // 跳转到登录页
            this.$router.push({path: '/'});
        },
        /**
         * 确认签到
         */
        onConfirm() {
            this.data.ilsId = this.ilsId; // 日程ID
            this.data.itmId = this.itmId; // 项目ID
            this.data.type = this.type; // 类型：0-签到，1-签退
            // 确认签到
            this.$axios({
                method: 'POST',
                url: `/app/api/trainee/course/lesson/clock/${this.type === 0 ? 'in' : 'out'}`,
                data: this.data
            }).then(res => {
                this.showSingleButton = true;
                this.buttonType = 2;
            });
        },
        /**
         * 提交
         * @param flag
         */
        onSubmit(flag) {
            if (flag) {
                this.data.isProve = 1; // 需要证明
                this.onConfirm();
            } else {
                this.showSingleButton = true;
                this.buttonType = 3;
                if (this.type === 0) {
                    this.tips = this.$t('schedule_tips_3');
                } else {
                    this.tips = this.$t('schedule_tips_4');
                }
            }
        },
        /**
         * 重试
         */
        onRetry() {
            this.visibleModal = true;
            this.showSingleButton = false;
            this.$refs.faceRef && this.$refs.faceRef.reIdentification();
        },
        /**
         * 人脸识别成功
         */
        takePictures() {
            this.visibleModal = false;
            this.showSingleButton = true;
            this.buttonType = 2;
        },
        /**
         * 人脸识别错误
         */
        takingError() {
            this.closeFace();
        },
        /**
         * 关闭人脸
         */
        closeFace() {
            this.visibleModal = false;
            this.showSingleButton = false;
            this.$refs.faceRef && this.$refs.faceRef.closeCamera();
        },
        /**
         * 前往报名
         */
        onRegistered() {
            this.$router.replace({path: `/certifiedCourse/${this.itmId}/0`});
        },
        /**
         * 继续
         */
        onContinue() {
            this.isAllow = true;
            this.showSingleButton = true;
            this.isLoading = true;
            this.getDetail();
        }
    },
    mounted() {
        this.title = this.type === 0 ? this.$t('training_sign_in') : this.$t('training_sign_off');
        // 设置人脸识别的busId
        window.localStorage.removeItem('face_busId');
        window.localStorage.setItem('face_busId', this.$route.params.ilsId);
        // 初始化
        this.init();
    }
};
</script>

<style scoped lang="less">
.van-col-text {
    padding: 10px 0;
}
.van-col-text:nth-child(odd) {
    text-align: right;
}
.van-col-text:nth-child(even) {
    text-align: left;
}
.bottom-button {
    width:100%;
    background:#fff;
    position: fixed;
    bottom: 0;
    border-top: 1px solid rgb(204, 204, 204);
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    .btn {
        height: 40px;
        text-align: center;
        line-height: 40px;
        background: #075ebb;
        color: #ffffff;
        border-radius: 4px;
    }
    .single-button {
        width: 100%;
        padding: 20px 0;
        .btn {
            display: inline-block;
            width: 60%;
        }
        .tips {
            width: 80%;
            margin: 20px auto auto;
            text-align: left;
        }
    }
    .multiple-button {
        width: 100%;
        padding: 20px 0;
        display: flex;
        justify-content: center;
        .btn {
            width: 150px;
        }
        .btn:first-child {
            margin-right: 10px;
        }
        .btn:last-child {
            margin-left: 10px;
        }
    }
}
</style>
